package com.winchain.chainbill.bill.biz.transfer.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICallback;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbStats;
import com.winchain.chainbill.bill.base.po.CbXfe;
import com.winchain.chainbill.bill.base.service.CbStatsService;
import com.winchain.chainbill.bill.biz.Bill;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.util.StringUtil;

@Component
public class BillXfeStatsCmd implements ICommand<Bill<CbXfe>>, ICallback<Bill<CbXfe>, AcctTxRec> {
	@Autowired
	private CbStatsService cbStatsService;

	public boolean execute(CommandContext<Bill<CbXfe>> context) throws Exception {
		Object timeOut = context.getValue("Timeout");
		if ((timeOut != null) && (((Boolean) timeOut).booleanValue())) {
			return false;
		}
		CbRec record = ((Bill) context.getSource()).getRec();
		CbStats stats = (CbStats) this.cbStatsService.selectByKey(record.getRootId());
		int chdNum = stats.getChdNum().intValue();
		int xfeFreq = stats.getXfeFreq().intValue();

		List<Bill<CbXfe>> children = (List) context.getValue("children");
		if ((children != null) && (children.size() > 0)) {
			chdNum += children.size();
			for (Bill<CbXfe> bill : children) {
				if (StringUtil.isNotEmpty(((CbXfe) bill.getSource()).getSellerId())) {
					xfeFreq += 1;
				}
			}
		} else {
			xfeFreq += 1;
		}
		stats.setChdNum(Integer.valueOf(chdNum));
		stats.setXfeFreq(Integer.valueOf(xfeFreq));
		if (stats != null) {
			this.cbStatsService.updateAll(stats);
		}
		return false;
	}

	public boolean callback(CallbackContext<Bill<CbXfe>, AcctTxRec> context) throws Exception {
		execute(context);
		return false;
	}
}
